import { getUserInfo, getUserInfoProfile } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { login } from '@/api/user'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(), // 存放token
    userInfo: {} // 存放用户信息
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      // 存放token
      setToken(token)
    },
    // 清空token
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 人员信息
    updateUser(state, info) {
      state.userInfo = info
      console.log(info)
    },
    // 清空用户信息
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 获取人员信息
    async updataUserInfo(context) {
      try {
        const res = await getUserInfoProfile()
        // console.log(res)
        const get = await getUserInfo(res.data.userId)
        // console.log(get)
        context.commit('updateUser', { ...res.data, ...get.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error, 'error')
      }
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
      resetRouter()
    },
    async newLogin(context, loginForm) {
      // 2 发送axios
      const res = await login(loginForm)
      console.log(res)
      // 3判断是否请求错误
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken', res.data)
    }
  }
}
